package com.zHan.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zHan.dto.QueryPageDto;
import com.zHan.mapper.ArticleMapper;
import com.zHan.pojo.Article;
import com.zHan.pojo.PageBean;
import com.zHan.pojo.Result;
import com.zHan.service.ArticleService;
import com.zHan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * ClassName: ArticleServiceImpl
 * Description:
 * date: 2023/11/9 0009 19:34
 *
 * @author zHan
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增文章
     *
     * @param article
     * @return
     */
    @Override
    public Result add(Article article) {
        // 补全参数
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        // 获取用户id
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        article.setCreateUser(id);
        // 新增
        articleMapper.insert(article);
        return Result.success("文章发布成功");
    }

    /**
     * 文章列表(条件分页)
     *
     * @param dto
     * @param categoryId
     * @param state
     * @return
     */
    @Override
    public Result<PageBean<Article>> queryPage(QueryPageDto dto, Integer categoryId, String state) {
        // 获取参数
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        // 创建PageBean对象
        PageBean<Article> pageBean = new PageBean<>();
        // 获取用户id
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        // 开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);
        // 调用Mapper
        List<Article> articleList = articleMapper.list(userId, categoryId, state);
        Page<Article> page = (Page<Article>) articleList;
        // 封装数据
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return Result.success(pageBean);
    }

    /**
     * 获取文章详情
     *
     * @param id
     * @return
     */
    @Override
    public Result findById(Integer id) {
        Article article = articleMapper.selectById(id);
        return Result.success(article);
    }

    /**
     * 更新文章
     *
     * @param article
     * @return
     */
    @Override
    public Result update(Article article) {
        articleMapper.update(article);
        return Result.success("文章修改成功");
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        articleMapper.delete(id);
        return Result.success("文章删除成功");
    }
}
